//
//  ViewController.m
//  Participation
//
//  Created by 王少宁 15/3/18.
//  Copyright (c) 2015年 BLUEBLACK. All rights reserved.
//  参与

#import "ParticipationViewController.h"
#import "ParticipationTabelViewCell.h"
#import "ParticipationDataManager.h"
#import "HDTabViewController.h"
#import "HDChatLIstController.h"
#import "JKReporter.h"
#import "SNSystemNotifyController.h"        //系统通知
#import "HZGoodsSalesViewController.h"      //web页面
#import "HZGoodsDetailViewController.h"     //商品详情
#import "HZMallGoodsListViewController.h"   //商品列表

#define LIMIT 15  //每一次请求多少条数据
#define kRefreshDataSelfTime 60 * 60 //自动刷新时间 (1个小时 , 以 s 为单位)

@interface ParticipationViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic,retain) UITableView * myTableView;
@property (nonatomic, retain) ParticipationHttpResult * result;
@property (nonatomic, retain) ParticipationDataManager * manager;
@property (nonatomic, assign) int viewApperCount;


@end

@implementation ParticipationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.barTintColor = nil;
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    self.navigationController.navigationBar.backgroundColor = HZ_CLEAR_COLOR;
    
    UIButton * chatBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.ubo fx:1 ox:20 fy:0],
                                                                  [self.ubo ow:40 oh:40])];
    [chatBtn setImage:[UIImage imageNamed:@"chat_gz"] forState:UIControlStateNormal];
    chatBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [chatBtn addTarget:self action:@selector(rightBarBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:chatBtn];
    
    self.viewApperCount = 0;
    [self createTableView];
    
    self.result = [[ParticipationHttpResult alloc] initWithTarget:self action:@selector(loadingData:)];
    self.manager = [ParticipationDataManager shareManager];
    [self refreshData];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    
    if (self.APNSKey) {
        [self refreshData];
    } else {
        if (self.viewApperCount) {
            NSTimeInterval aTimer = [[NSDate date] timeIntervalSinceDate:[[SNBaseInfoManager shareManager] baseInfoObjectForKey:kLastRequestParticiPationDataTime]];
            if (aTimer > kRefreshDataSelfTime) {
                [self refreshData];
            }
        }
    }
    
    self.viewApperCount++;
}

#pragma mark - 初始化 tableView
- (void)createTableView
{
    self.myTableView = CREATE_WITH_FRAME_OF(UITableView, CGPointMake(0, 0),
                                            [self.view.ubo fw:1.0 fh:1.0],
                                            style:UITableViewStylePlain);
    self.myTableView.backgroundColor = [XCommon hexStringToColor:kColor_lightGray_cell];
    self.myTableView.contentInset = _myTableView.scrollIndicatorInsets =  UIEdgeInsetsMake(self.navigationAndStatusBarHeight, 0, ktabBarHeight, 0);
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.separatorColor = [UIColor clearColor];
    self.myTableView.headerRefreshController = [[UIRefreshHeaderController alloc] initWithTableView:self.myTableView caller:[UBTargetCaller of:self action:@selector(refreshData)]];
    self.myTableView.footerRefreshController = [[UIRefreshFooterController alloc] initWithTableView:self.myTableView caller:[UBTargetCaller of:self action:@selector(loadMoreData)]];
    self.myTableView.nothingRefreshView = [[UIRefreshNotingRefreshView alloc] initWithView:self.myTableView viewController:self tryAgain:@selector(refreshData)];
    [self.view addSubview:self.myTableView];
}

- (void)refreshData
{
    [self requestWithAsiWithID:0 flag:0];
}

#pragma mark - 下拉加载
- (void)loadMoreData
{
    ParticipationModel * model = [self.result.dataArray lastObject];
    [self requestWithAsiWithID:[model.ID intValue]flag:1];
}

#pragma mark -发送异步请求
- (void) requestWithAsiWithID:(int)ID flag:(int)flag
{
    NSString * myAreaID = [[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaID] && [[[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaID] length] ? [[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaID] : @"0";
    
    if (self.viewApperCount == 0 || ![myAreaID isEqualToString:[[SNBaseInfoManager shareManager] baseInfoObjectForKey:kLastRequestMainPageCmid]]) {//首次进入参与页面或者更换了cmid,重新加载数据.并显示转菊花
        [self.myTableView.nothingRefreshView show];
    }
    
    [self.manager loadParticipationData:self.result flag:flag Id:ID limit:LIMIT cmid:myAreaID];
}

#pragma mark - 数据处理
- (void)loadingData:(ParticipationHttpResult *)result
{
    [self.myTableView endRefreshingAll];
    if (result.success) {
        [self.myTableView.nothingRefreshView remove];
        [self.myTableView reloadData];
    } else if (result.failure) {
        [self.myTableView.nothingRefreshView activeStop];
    }
}

#pragma mark 消息列表
- (void)rightBarBtnClicked:(id)sender{
    
    if ([SNTool shouldLoginFromController:self]) {
        return;
    }
    
    HDChatLIstController * chatList = [[HDChatLIstController alloc]init];
    chatList.hidesBottomBarWhenPushed = YES;
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"firstChat"]integerValue] == 0) {
        chatList.chatSign = @"0";
    }else
    {
        chatList.chatSign = @"1";
    }
    
    [self.navigationController pushViewController:chatList animated:YES];
}

#pragma mark - tabelView 代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.result.noMoreData) {
        return self.result.dataArray.count+1;
    } else {
        return self.result.dataArray.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < self.result.dataArray.count) {
        static NSString * particapationTabelCellIdentifier = @"particapationTabelCell";
        ParticipationTabelViewCell * cell = [tableView dequeueReusableCellWithIdentifier:particapationTabelCellIdentifier];
        
        if (cell == nil) {
            cell = [[ParticipationTabelViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:particapationTabelCellIdentifier];
        }
        
        cell.backgroundColor = [XCommon hexStringToColor:kColor_lightGray_cell];
        
        ParticipationModel * model = self.result.dataArray[indexPath.row];
        [cell cellWithModel:model];
        
        return cell;
    } else {
        NoMoreDataCell * cell = [[NoMoreDataCell alloc] init];
        cell.backgroundColor = [XCommon hexStringToColor:kColor_lightGray_cell];
        return cell;
    }
}

#pragma mark - cell 的跳转
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.result.dataArray.count) {
        return;
    }
        
    [self.myTableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ParticipationModel * model = self.result.dataArray[indexPath.row];
    
    if ([model.mtype isEqualToString:@"1"]) { //系统通知
        
        SNSystemNotifyController * systemNotifyVC = [[SNSystemNotifyController alloc] init];
        systemNotifyVC.titleStr = model.title;
        systemNotifyVC.contentStr = model.content;
        systemNotifyVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:systemNotifyVC animated:YES];
        
    } else if ([model.mtype isEqualToString:@"2"]) { //web 页面
        
        SNPartLinkDataWebModel * webModel = (SNPartLinkDataWebModel *)model.linkDataModel;
        HZGoodsSalesViewController *salesVC = [[HZGoodsSalesViewController alloc] init];
        salesVC.webTitle = model.title;
        salesVC.webURL = webModel.url;
        salesVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:salesVC animated:YES];
        
    } else if ([model.mtype isEqualToString:@"3"]) { //商品列表
        
        SNPartLinkDataListModel * listModel = (SNPartLinkDataListModel *)model.linkDataModel;
        HZMallGoodsListViewController *mallGoodsListVC = [[HZMallGoodsListViewController alloc] init];
        mallGoodsListVC.actID = listModel.actid;
        mallGoodsListVC.actName = model.name;
        mallGoodsListVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:mallGoodsListVC animated:YES];
        
    } else if ([model.mtype isEqualToString:@"4"]) { //商品详情
        
        SNPartLinkDataDetailModel * detailModel = (SNPartLinkDataDetailModel *)model.linkDataModel;
        HZGoodsDetailViewController *detailVC = [[HZGoodsDetailViewController alloc] init];
        detailVC.shopID = detailModel.shop_id;
        detailVC.productID = detailModel.product_id;
        detailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
        
    }
    
}

#pragma mark - cell 高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < self.result.dataArray.count) {
        ParticipationModel * model = self.result.dataArray[indexPath.row];
        return model.cellHeight;
    } else {
        return kNoMoreDataCellHeight;
    }
}

//-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
//{
//    if (!(self.myTableView.contentOffset.y < 0) || !((self.myTableView.contentOffset.y) > ((self.myTableView.contentSize.height) - (self.myTableView.frame.size.height)))) {
//        [[SDImageCache sharedImageCache] clearMemory];
//    }
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
